<?php   
class Db{
 
 
	//1.私有的静态属性
  	private static $link; 
  	private $table_name;
  	private $objdb;
  	private $options;
 
  	//初始化
    private function __construct(){
        //为了方便演示，数据库配置直接在了下面，各位同行，可以自行写成配置，这里不再赘述
    	$hostfield = 'localhost';
    	$userfield = 'shops';
    	$password = 'shops';
    	$datebase = 'shops';
    	$objdb = mysqli_connect($hostfield,$userfield,$password,$datebase);
    	// 修改数据库连接字符集为 utf8
		  mysqli_set_charset($objdb,"utf8");
    	// 检测连接
  		if (!$objdb) {
  		    die("Connection failed: " . mysqli_connect_error());
  		}
    	$this->objdb = $objdb;
    	return $this->objdb;
    }
 
 
    //静态公共接口
    public static function getInstance(){
    	if(!(self::$link instanceof self)){ 
    	 	self::$link = new self(); 
    	}  
	    return self::$link;
    }
 
 
 
    //返回数据库实例对象
    public static function table($table_name){
        $link = self::getInstance();
        $link->table_name = $table_name;
        return $link;
    }
 
 
    //field:格式->('id,name,time......')
    public function field($field){
   		$this->options['field'] = $field;
   		return $this;
    }
 
    //处理field数据，组sql
    public function deal_field($field){
        $field = $field['field'];
   		return $field;
    }
 
 
    //设置where条件(数组和多个where都可以)，where('id',12)  or where([id=>12])
    public function where($key,$factor='',$val=''){
   		$v = (string)$val;
   		if($key != '' && $factor != '' && $v != ''){//属于三者都有的情况，中间的参数就是条件
   			if(is_string($key) && is_string($factor) && is_string($v)){
   				$v_str = "`$key` $factor '$val'";
   			}else{
   				die("failed: ".'不合法');
   			}
   		}else{//两个或者一个参数的情况
   			$val = (string)$factor;//此种情况将第二参数传给第三个参数
   			if(is_string($key) && !is_array($key)){//为字符串
	   			$v_str = "`$key`='$val'";
	   		}else if(is_array($key)){
	   			$count_key = count($key);
	   			$nums = 1;
	   			$str = '';
	   			foreach($key as $k=>$v){
	   				if($count_key == $nums){
	   					$str .= "`$k`='$v'";
	   				}else{
	   					$str .= "`$k`='$v'".' '.'and'.' ';
	   				}
	   				$nums++;
	   			}
	   			$nums = 1;
	   			$v_str = $str;
	   		}else{
	   			die("failed: ".'不合法');
	   		}
   		}
   		$this->options['where'][] = $v_str;
   		return $this;
    }
 
    //处理where数据，组sql
    public function deal_where($where){
   		$arr = $where['where'];
   		$count_key = count($arr);
   		$nums = 1;
   		$str = '';
   		foreach($arr as $key=>$val){
   			if($count_key == $nums){
   				$str .= $val;
   			}else{
   				$str .= $val.' '.'and'.' ';
   			}
			$nums++;
   		}
   		$nums = 1;
   		return 'where '.$str;
    }
 
 
    //设置排序 格式->('id desc,time aes')      //ORDER BY ticketnum_id desc,project_id desc
    public function order($order){
   		$this->options['order'] = $order;
   		return $this;
    }
 
    //处理order数据，租sql
    public function deal_order($order){
   		$order = $order['order'];
   		return 'ORDER BY '.$order;
    }
 
 
    //设置分页查询、格式->('0,10')
    public function limit($limit,$nums=''){
    if((string)$nums == '' && (string)$limit != ''){
        $this->options['limit'] = '0'.','.(string)$limit;
    }else{
        $this->options['limit'] = (string)$limit.','.(string)$nums;
    }
   		return $this;
    }
 
    //处理limit数据，租sql
    public function deal_limit($limit){
        $limit = $limit['limit'];
        return 'limit '.$limit;
    }
 
 
 
    //查找单条
    public function find(){
        $link = self::getInstance()->objdb;
        $table = $this->table_name;
        $array = $this->do_sql();
        $field = isset($array['field'])?$array['field']:'*';
        $make = isset($array['make'])?$array['make']:'';
        $sql = 'select '.$field.' from '.$table.' '.$make;
        $result = mysqli_query($link,$sql);
        $arr = [];
        if($result && mysqli_num_rows($result)>0){
            $arr = mysqli_fetch_assoc($result);
        }
        //$this->close_db($link);
        return $arr;
    }
 
 
    //查询多条
    public function select(){
      $link = self::getInstance()->objdb;
   		$table = $this->table_name;
        $array = $this->do_sql();
        $field = isset($array['field'])?$array['field']:'*';
        $make = isset($array['make'])?$array['make']:'';
   		$sql = 'select '.$field.' from '.$table.' '.$make;
   		
   	//	echo $sql;exit;
   		$result = mysqli_query($link,$sql);
   		$arr = [];
   		if($result && mysqli_num_rows($result)>0){
		    while($row=mysqli_fetch_assoc($result)){
		        $arr[] = $row;
		    }
		}
		//$this->close_db($link);
   		return $arr;
    }
 
 
    //处理options，组成sql语句(公共函数)
    public function do_sql(){
        $array = $this->options;
        if(empty($array)){
            return [];
        }
        $this->options = [];//清除记录
        $data = []; $stra = ''; $strb = '';
        foreach ($array as $key => $val) {
            $deal_something = 'deal_'.$key;
            if($key == 'field'){
                $stra .= $this->$deal_something($array).' ';
                $data['field'] = $stra;
            }else{
                $strb .= $this->$deal_something($array).' ';
                $data['make'] = $strb;
            }
        }
        return $data;
    }
 
 
 
    //添加插入数据 $add:数组(['xxx'=>'xxx','xxxx'=>'xxxx'])  
    public function add($add){
        if(!is_array($add)){
            return false;
        }
        $data = $this->deal_add($add);
        $link = self::getInstance()->objdb;
        $table = $this->table_name;
        $sql = 'INSERT INTO '.$table.' '.$data['key'].' VALUES '.$data['val'];
        //echo  $sql; exit;
        $result = mysqli_query($link,$sql);
        if($result && mysqli_affected_rows($link)>0){
            $res = mysqli_insert_id($link);
            //$this->close_db($link);
            return $res;
        }else{
            return false;
        }
    }
 
    //处理add的数据，租sql
    public function deal_add($add){
        $nums = 1;
        $counts = count($add);
        $stra = ''; $strb = '';
        foreach($add as $key=>$val){
            if($nums == 1){
                $stra .= '('.(string)$key;
                $strb .= '('.(string)"'$val'";
            }elseif($nums == $counts){
                $stra .= ','.(string)$key.')';
                $strb .= ','.(string)"'$val'".')';
            }else{
                $stra .= ','.(string)$key;
                $strb .= ','.(string)"'$val'";
            }
            $nums++;
        }
        $data['key'] = $stra;
        $data['val'] = $strb;
        return $data;
    }
 
 
 
 
 
 
    public function update($data){
        if(!is_array($data)){
            return false;
        }
        $data = $this->deal_update($data);
        $link = self::getInstance()->objdb;
        $table = $this->table_name;
        $array = $this->do_sql();
        $make = isset($array['make'])?$array['make']:'';
        $sql = 'UPDATE '.$table.' SET '.$data.' '.$make;
        $result = mysqli_query($link,$sql);
        $effet = mysqli_affected_rows($link);
        if($result && $effet>0){
            $res = $effet;
            //$this->close_db($link);
            return $res;
        }else{
            return false;
        }
    }
 
 
    public function deal_update($data){
        $nums = 1;
        $counts = count($data);
        $str = '';
        foreach($data as $key=>$val){
            if($nums == $counts){
                $str .= $key.' = '.(string)"'$val'";
            }else{
                $str .= $key.' = '.(string)"'$val'".' , ';
            }
            $nums++;
        }
        return $str;
    }
 
     public static function   dels($sqls){
 
        $link = self::getInstance()->objdb;
  
        
        $res = mysqli_query($link,$sqls);
        if($res && mysqli_affected_rows($link)){
            return mysqli_affected_rows($link);
        }else{
            return false;
        }
    }
 
 
 
    public function del(){
        $data = $this->deal_del();
        $link = self::getInstance()->objdb;
        $table = $this->table_name;
        $sql = 'DELETE FROM '.$table.' '.$data;
        
         
        
        $res = mysqli_query($link,$sql);
        if($res && mysqli_affected_rows($link)){
            return mysqli_affected_rows($link);
        }else{
            return false;
        }
    }
 
 
    public function deal_del(){
        $array = $this->options;
        if(empty($array)){
            return '';
        }
        $res = $this->deal_where($array);
        return $res;
    }
 
 
 
 
 
    public function close_db($link){
    	mysqli_close($link);
    }
 
}

?>